﻿using Log.Recorder.Entity;
using Newtonsoft.Json;
using System.IO;

namespace Log.Recorder
{
    /// <summary>
    /// 配置文件
    /// </summary>
    class LogConfig
    {
        
        #region 获取程序的基目录
        /// <summary>
        /// 获取程序的基目录 。如 E:\\workspace\\gitee\\LogRecorder\\Demo\\
        /// </summary>
        public static string BaseDirectory
        {
            get { 
                return System.AppDomain.CurrentDomain.BaseDirectory;
            }
        }
        #endregion


        /// <summary>
        /// 配置文件名
        /// </summary>
        private static string _ConfigFileName = "Log.Recorder.json";
        /// <summary>
        /// 配置信息
        /// </summary>
        private static LogConfigInfo _ConfigInfo = null;
        /// <summary>
        /// 默认配置信息
        /// </summary>
        private static LogConfigInfo DefaultConfigInfo {
            get
            {
                return new LogConfigInfo()
                {
                    LogDbPathRoot = BaseDirectory,
                    LogLevel = "Off"
                };
            }
        }


        /// <summary>
        /// 刷新配置信息
        /// </summary>
        public static void RefreshLogConfigInfo() {
            
            try
            {
                string configJsonString = "";
                string configUrl = BaseDirectory + _ConfigFileName;
                if (File.Exists(configUrl))
                {
                    configJsonString = File.ReadAllText(configUrl);
                }
                else {
                    configUrl = BaseDirectory + "bin\\"+ _ConfigFileName;
                    if (File.Exists(configUrl))
                    {
                        configJsonString = File.ReadAllText(configUrl);
                    }
                }

                //记录日志记录器配置文件不存在，使用默认配置
                if (!string.IsNullOrEmpty(configJsonString))
                {
                    JsonSerializerSettings settings = new JsonSerializerSettings();
                    settings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                    _ConfigInfo = JsonConvert.DeserializeObject<LogConfigInfo>(configJsonString);

                    if (_ConfigInfo != null)
                    {

                        if (string.IsNullOrEmpty(_ConfigInfo.LogDbPathRoot))
                        {
                            _ConfigInfo.LogDbPathRoot = BaseDirectory;
                        }
                        else
                        {
                            _ConfigInfo.LogDbPathRoot = _ConfigInfo.LogDbPathRoot.Trim();

                            if (!(_ConfigInfo.LogDbPathRoot.EndsWith("\\") || _ConfigInfo.LogDbPathRoot.EndsWith("/")))
                            {
                                _ConfigInfo.LogDbPathRoot += "\\";
                            }
                        }

                        if (string.IsNullOrEmpty(_ConfigInfo.LogLevel))
                        {
                            _ConfigInfo.LogLevel = "Off";
                        }
                        else
                        {
                            _ConfigInfo.LogLevel = _ConfigInfo.LogLevel.Trim();
                            if (string.IsNullOrEmpty(_ConfigInfo.LogLevel))
                            {
                                _ConfigInfo.LogLevel = "Off";
                            }
                        }
                    }
                }
                else {
                    _ConfigInfo = DefaultConfigInfo;
                }
                
            }
            catch (System.Exception exp)
            {
                _ConfigInfo = DefaultConfigInfo;
                using (InternalLogRecorder ilog = new InternalLogRecorder())
                {
                    ilog.InternalLog("记录日志记录器配置文件异常。", exp);
                }
            }
            //默认配置
            if (_ConfigInfo == null)
            {
                _ConfigInfo = DefaultConfigInfo;
            }
        }

        #region 监控配置文件

        private static FileSystemWatcher watcher = null;
        /// <summary>
        /// 
        /// </summary>
        private static void WatchConfigFile() {
            if (watcher == null) {
                watcher = new FileSystemWatcher(BaseDirectory);
                watcher.NotifyFilter =// NotifyFilters.Attributes
                                 //| NotifyFilters.CreationTime
                                 //| NotifyFilters.DirectoryName
                                 //| NotifyFilters.FileName
                                 //| NotifyFilters.LastAccess
                                // | 
                                 NotifyFilters.LastWrite
                                 //| NotifyFilters.Security
                                | NotifyFilters.Size ;
                
                watcher.Changed += OnChanged;
                watcher.Created += OnCreated;
                watcher.Deleted += OnDeleted;
                watcher.Renamed += OnRenamed;
                //watcher.Error += OnError;

                watcher.Filter = _ConfigFileName;
                watcher.IncludeSubdirectories = true;
                watcher.EnableRaisingEvents = true;

            }
        }

        private static void OnChanged(object sender, FileSystemEventArgs e)
        {
            if (e.ChangeType == WatcherChangeTypes.Changed)
            {
                RefreshLogConfigInfo();
            }
        }
        private static void OnCreated(object sender, FileSystemEventArgs e)
        {
            if (e.ChangeType == WatcherChangeTypes.Created)
            {
                RefreshLogConfigInfo();
            }
        }

        private static void OnDeleted(object sender, FileSystemEventArgs e) {
            if (e.ChangeType == WatcherChangeTypes.Deleted)
            {
                RefreshLogConfigInfo();
            }
        }

        private static void OnRenamed(object sender, RenamedEventArgs e)
        {
            if (e.ChangeType == WatcherChangeTypes.Renamed)
            {
                RefreshLogConfigInfo();
            }
        }
        //private static void OnError(object sender, ErrorEventArgs e)
        //{
        //    RefreshLogConfigInfo();
        //}

        #endregion




        /// <summary>
        /// 配置信息
        /// </summary>
        public static LogConfigInfo ConfigInfo
        {
            get {
                if (_ConfigInfo == null) {
                    RefreshLogConfigInfo();
                    WatchConfigFile();
                }
                return _ConfigInfo == null ? DefaultConfigInfo : _ConfigInfo;
            }
        }

        /// <summary>
        /// 日志文件根目录
        /// </summary>
        public static string LogDbPathRoot
        {
            get
            {
                return ConfigInfo.LogDbPathRoot + "LogRecorderSQlites\\";
            }
        }
        /// <summary>
        /// 获取配置日志等级
        /// </summary>
        public static string LogLevel
        {
            get
            {
                return ConfigInfo.LogLevel;
            }
        }
    }
}
